'use client';
import {
	useImperativeHandle,
	useState,
	useCallback,
	forwardRef,
	useEffect,
	useRef
} from 'react';
import { useAppSelector, useAppDispatch } from '@/store/hooks';
import { addhistoryData, addListData, setClear } from '@/store/initSlice';
import { useRouter, usePathname } from 'next/navigation';
import http, { baseUrl } from '@/lib/request';
import { getSesstion } from '@/lib/session';
import { ApiResponse, MessageData } from '@/types/interface';

interface Props {
	id?: string;
}

// 自定义图标组件
const ArrowUpIcon = () => (
  <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 10l7-7m0 0l7 7m-7-7v18" />
  </svg>
);

const PauseCircleIcon = () => (
  <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
  </svg>
);

const UploadIcon = () => (
  <svg className="w-6 h-6 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
  </svg>
);

// 控制器中止（支持中止流式请求）
let controller = new AbortController();
// 控件组件
const SearchItem = forwardRef(({ id }: Props, ref) => {
	// 使用useState管理表单状态
	const [text, setText] = useState('');
	const [uploadedFile, setUploadedFile] = useState<File | null>(null);
	const fileInputRef = useRef<HTMLInputElement>(null);
	
	const dispatch = useAppDispatch();
	const router = useRouter();
	const pathname = usePathname();

	const [conversationId, setConversationId] = useState('');
	const [isPlaying, setIsPlaying] = useState(false);
	const [disabled, setDisabled] = useState(true);

	// 表单字段变化检查
	useEffect(() => {
		// 当文本或文件有内容时启用按钮
		setDisabled(!(text.trim() || uploadedFile));
	}, [text, uploadedFile]);

	// 获取历史会话内容
	const fetchMessages = useCallback(
		async (id: string) => {
			const res = await http.get(`${baseUrl}/perf/session/messgaes/${id}`);
			const result = res as ApiResponse<MessageData>;
			dispatch(addhistoryData(result.data));
		},
		[dispatch],
	);

	// 停止播放任务
	const stopTask = () => {
		dispatch(setClear(false));
		setIsPlaying(false);
		controller.abort(); // 停止流请求
		dispatch(addListData([]));
	};

	// 用于父组件调用：公开方法
	useImperativeHandle(ref, () => ({
		handleStop: stopTask,
		handleClickData: (isNew: boolean, id: string) => {
			dispatch(setClear(false));
			setConversationId(id);
			if (isNew) {
				dispatch(addhistoryData({}));
				stopTask();
			} else {
				fetchMessages(id);
			}
		},
	}));

	// 处理文件选择
	const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const files = e.target.files;
		if (files && files.length > 0) {
			setUploadedFile(files[0]);
		}
	};
	
	// 重置表单
	const resetForm = () => {
		setText('');
		setUploadedFile(null);
		if (fileInputRef.current) {
			fileInputRef.current.value = '';
		}
	};

	// 提交处理
	const onFinish = async () => {
		console.log(conversationId);
		let id = conversationId || crypto.randomUUID();
		const payload = {
			file_name: uploadedFile?.name || '',
			weather_data_filler: text,
			conversation: id,
		};

		if (!pathname.includes(id)) router.push(`/report/${id}`);
		if (!(payload.file_name || payload.weather_data_filler)) return;
		fetchMessages(id);
		setConversationId(id);
		setIsPlaying(true);
		controller = new AbortController();
		dispatch(setClear(true));
		for (let key in payload) {
			//@ts-ignore
			if (!payload[key]) {
				//@ts-ignore
				delete payload[key];
			}
		}

		try {
			resetForm();
			setDisabled(true);
			const res = await http.post(
				`${baseUrl}/perf/session/start_report`,
				payload,
				{
					signal: controller.signal,
				},
			);
			const reader = res.body?.getReader();
			if (!reader) return;

			const decoder = new TextDecoder();
			let remark = '',
				node = '';
			const cachedList: any[] = [];
			const process = async ({ done, value }: any): Promise<any> => {
				if (done) {
					stopTask();
					return;
				}
				try {
					const text = decoder.decode(value);
					const parts = text.split('\n\n');
					const resultList: any[] = [];

					for (let part of parts) {
						if (part.startsWith('data: ')) {
							const payload = JSON.parse(part.slice(6).trim());
							if (!payload.remark) {
								payload.remark = remark;
								payload.node = node;
							} else {
								remark = payload.remark;
								node = payload.node;
							}
							resultList.push(payload);
						}
					}

					if (!window.location.href.includes(id)) {
						cachedList.push(...resultList);
					} else {
						dispatch(addListData([...cachedList, ...resultList]));
						cachedList.length = 0;
					}
				} catch (e) {
					console.error('流处理出错:', e);
				}
				return reader.read().then(process);
			};

			reader.read().then(process);
		} catch (e) {
			console.error('请求失败或已中止:', e);
			dispatch(setClear(false));
			stopTask();
		}
	};

	return (
		<div className="relative px-40">
			<div className="shadow bg-gray-100 p-4 rounded-2xl relative">
				{/* 文本输入区 */}
				<textarea
					value={text}
					onChange={(e) => setText(e.target.value)}
					rows={2}
					placeholder="请输入文本或上传文件"
					className="w-full resize-none bg-transparent focus:outline-none text-gray-800"
				/>
				
				{/* 文件上传区 */}
				<div className="mt-4 flex items-center">
					{/* 隐藏的文件输入 */}
					<input
						type="file"
						ref={fileInputRef}
						onChange={handleFileChange}
						className="hidden"
						accept=".txt,.pdf,.doc,.docx,.xls,.xlsx,.csv"
					/>
					
					{/* 上传按钮 */}
					<button
						type="button"
						onClick={() => fileInputRef.current?.click()}
						className="mr-4 p-2 cursor-pointer text-blue-500 hover:text-blue-600 transition-colors"
						aria-label="上传文件"
					>
						<UploadIcon />
					</button>
					
					{/* 已上传文件显示 */}
					{uploadedFile && (
						<div className="text-sm text-gray-600">
							已选择: {uploadedFile.name}
						</div>
					)}
				</div>
				
				{/* 操作按钮 */}
				{isPlaying ? (
					<button
						className="absolute right-5 bottom-2 cursor-pointer p-2 rounded-full bg-red-500 text-white hover:bg-red-600 transition-colors"
						onClick={stopTask}
						aria-label="停止"
					>
						<PauseCircleIcon />
					</button>
				) : (
					<button
						className="absolute right-5 bottom-2 cursor-pointer p-2 rounded-full bg-blue-500 text-white hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
						disabled={disabled}
						onClick={onFinish}
						aria-label="发送"
					>
						<ArrowUpIcon />
					</button>
				)}
			</div>

			<div className="text-center py-2 text-gray-600">AI生成</div>
		</div>
	);
});

SearchItem.displayName = 'SearchItem';

export { SearchItem };
